package cn.thinkjoy.LawDataForExcel.extractURL;

import cn.thinkjoy.LawDataForExcel.bean.CompanyInfo;
import cn.thinkjoy.LawDataForExcel.util.UtilCode;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;

import java.io.IOException;

/**
 * Created by thinkjoy on 2017/6/19.
 */
public class HtmlUnitSearchWeb{

    private WebClient webClient;
    private String purl;
    private String value;
    private String cvalue;
    private CompanyInfo companyInfo;

    public HtmlUnitSearchWeb(String value,String cvalue) {
        this.webClient =new WebClient();
        this.purl = "http://www.tianyancha.com/search?key=";
        this.value = value;
        this.cvalue=cvalue;
        this.companyInfo=new CompanyInfo();
    }
    /**
     * 初始化客户端
     */
    public void initClient(){
        webClient.getOptions().setUseInsecureSSL(true);//支持https
        webClient.getOptions().setJavaScriptEnabled(true); // 启用JS解释器，默认为true
        webClient.getOptions().setCssEnabled(false); // 禁用css支持
        webClient.getOptions().setThrowExceptionOnScriptError(false); // js运行错误时，是否抛出异常
        webClient.getOptions().setTimeout(60000); // 设置连接超时时间 ，这里是一分钟。如果为0，则无限期等待
        webClient.getOptions().setDoNotTrackEnabled(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX
//            webClient.setJavaScriptTimeout(8000);//设置js运行超时时间
//            webClient.waitForBackgroundJavaScript(500);//设置页面等待js响应时间,
    }

    /**
     * 天眼通网页数据爬取
     */
    public CompanyInfo AdvanceSearch(){
        try {
            initClient();
            StringBuffer sb=new StringBuffer();
            sb.append(purl);
            sb.append(UtilCode.getURLEncoderString(value));
            sb.append("&checkFrom=searchBox");
            HtmlPage htmlPage=webClient.getPage(sb.toString());//获取页面源码
            System.out.println(htmlPage);
            DomNodeList<DomNode> pItemLists=htmlPage.querySelectorAll(".query_name");//查询结果页面
            int flag=0;
            for(DomNode node:pItemLists){
                HtmlAnchor anchor= (HtmlAnchor) node;
                String itemurl=anchor.getHrefAttribute().toString();//获取a标签的链接
                String text=anchor.asText().toString();
                if(text.indexOf("(")!=-1 && text.indexOf(")")!=-1){
                    text=text.replaceAll("\\(","").replaceAll("\\)","");
                }else if (text.indexOf("（")!=-1 && text.indexOf("）")!=-1){
                    text=text.replaceAll("（","").replaceAll("）","");
                }
                if(text.trim().equals(value)){
                    HtmlPage itemPage=webClient.getPage(itemurl);//详细内容页面
                    HtmlDivision division=itemPage.querySelector(".baseInfo_model2017");
                    if(division!=null){
                        HtmlDivision itemdiv=division.querySelector(".new-c3");
                        String legalname=null;
                        if(itemdiv!=null){
                            legalname=itemdiv.asText().toString();
                        }
                        DomNodeList<DomNode> lists=itemPage.querySelectorAll(".c8");
                        if(lists.size()>0){
                            for(DomNode itemnode:lists){
                                HtmlDivision div= (HtmlDivision) itemnode;
                                flag++;
                                if(flag>1){
                                    String content=null;
                                    if (div.asText().indexOf("：")!=-1){
                                        content=div.asText().substring(div.asText().indexOf("：")+1);
                                    }else if (div.asText().indexOf(":")!=-1){
                                        content=div.asText().substring(div.asText().indexOf(":")+1);
                                    }else content=div.asText();
                                    switch (flag){
                                        case 2: companyInfo.setRegistnumber(content.trim());break;
                                        case 3: companyInfo.setOrganiznumber(content.trim());break;
                                        case 4: companyInfo.setCreditnumber(content.trim());break;
                                        default: break;
                                    }
                                }
                                if(flag==4) break;
                            }
                        }
                        if(companyInfo.getRegistnumber()==null && companyInfo.getOrganiznumber()==null && companyInfo.getCreditnumber()==null){
                            return null;
                        }else {
                            companyInfo.setLegalname(legalname);
                            companyInfo.setCompanyname(cvalue);
                        }
                        return companyInfo;
                    }else {
                        return null;
                    }
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("信息获取失败");
            return null;
        }catch (NullPointerException e){
            System.out.println("信息获取失败");
            return null;
        }finally {
            webClient.close();
        }
        return null;
    }
}
